package com.zhongketech.sunflower.transport.im;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import android.util.Log;

import com.zhongketech.sunflower.Constant;
import com.zhongketech.sunflower.MyApplication;
import com.zhongketech.sunflower.MyToast;
import com.zhongketech.sunflower.transport.LogUtil;
import com.zhongketech.sunflower.transport.uitl.DataUtils;


public class ZKSocket{

	private static final String TAG = "ZKSocket";

	/**
	 * 接收消息线程间隔时间，单位ms
	 */
	public static final long RECEIVE_TIMEOUT = 10000;

	/**
	 * 心跳时间
	 */
	//	public static final long HEARTBEAT_TIMEOUT = 5000;
	public static final short COMMAND_HEARTBEAT = 0x0002;
	private static ZKSocket mZKSocket =  null;
	private static String ip = Constant.IM_SERVER;
	private static int port = Constant.IM_PORT;
	private String newMsg = "";
	private static Socket socket = null;
	//	private static Socket receiveSocket = null;
	//	private static InputStream inputStream = null;
	//	private static OutputStream outputStream = null;

	private ZKSocket()
	{

	}

	public static ZKSocket getInstance()
	{
		if(null == mZKSocket)
		{
			try {
				socket = new Socket(ip, port);
				mZKSocket = new ZKSocket();
				receiveMsgThread.start();
				//			sendHeartbeatThread.start();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				Log.i(TAG,"连接服务器失败:"+e);
				MyToast.getInstance().show("连接服务器失败:"+e);
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.i(TAG,"连接服务器失败:"+e);
				MyToast.getInstance().show("连接服务器失败:"+e);
				e.printStackTrace();
				return null;
			}
		}

		return mZKSocket;
	}

	public boolean handshake(String id,String token)
	{
		LogUtil.i(TAG,"Handshake id:"+id+" session_token:"+token);
		Map<String,String> map = new HashMap<String, String>();	
		map.put("id", id);
		map.put("session_token", token);

		final byte[] msg = DataPackage.composeMsg((short)9999, (short)0x004, map);
		try {
			send(msg);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			MyToast.getInstance().show("握手失败:"+e);
			e.printStackTrace();
		}

		return true;
	}

	private void send(byte[] content) throws InterruptedException  
	{  
		try {  
			LogUtil.i(TAG,"send content lenght:"+content.length);
			OutputStream ou = socket.getOutputStream();  
			//			ou.write(content.length);  
			ou.write(content);  
			ou.flush();  

		} catch (IOException e) {  
			MyToast.getInstance().show("发送失败:"+e);
			e.printStackTrace();  
		}  
	}  



	static Thread receiveMsgThread = new Thread()
	{
		public void run() {
			while(null != socket)
			{
				try {
					DataInputStream input = new DataInputStream(socket.getInputStream());
					byte[] buffer;
					buffer = new byte[input.available()];
					if(buffer.length != 0){
						while(true)
						{
							input.read(buffer);
							//							String msg = new String(buffer, "UTF-8");
							//							if(LogUtil.LogON)
							//							{
							//								for(int i = 0;i < buffer.length;i ++)
							//								{
							//									LogUtil.i("ZKCOCKET","receiveMsgThread["+i+"]"+buffer[i]);
							//								}
							//							}
							MsgDao msgDao =  DataPackage.analysisMsg(buffer);

							Log.i(TAG,"msg:"+msgDao.getBody());
							
							try {
								Thread.sleep(RECEIVE_TIMEOUT/2);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}


					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				}

				try {
					Thread.sleep(RECEIVE_TIMEOUT/2);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		};
	};

	//
	//	private static MsgDao receiveMsg()
	//	{
	//		try {
	//			DataInputStream input = new DataInputStream(socket.getInputStream());
	//			byte[] buffer;
	//			buffer = new byte[input.available()];
	//			if(buffer.length != 0){
	//				// 读取缓冲区
	//				input.read(buffer);
	//				String msg = new String(buffer, "UTF-8");
	////				if(LogUtil.LogON)
	////				{
	////					for(int i = 0;i < buffer.length;i ++)
	////					{
	////						LogUtil.i("ZKCOCKET","receiveMsgThread["+i+"]"+buffer[i]);
	////					}
	////				}
	//				DataPackage.analysisMsg(buffer);
	//			}
	//		} catch (IOException e) {
	//			// TODO Auto-generated catch block
	//			e.printStackTrace();
	//		}    
	//
	//		return null;
	//	}
	//
	//	static Thread sendHeartbeatThread = new Thread()
	//	{
	//		public void run() {
	//
	//			LogUtil.i("ZKCOCKET","sendHeartbeatThread start");
	//			try {
	//
	//				DataOutputStream output = new DataOutputStream(socket.getOutputStream());
	//			} catch (UnknownHostException e1) {
	//				// TODO Auto-generated catch block
	//				e1.printStackTrace();
	//			} catch (IOException e1) {
	//				// TODO Auto-generated catch block
	//				e1.printStackTrace();
	//			}
	//
	//			PrintWriter out = null;
	//			if (null != socket) 
	//			{
	//				try {
	//					out = new PrintWriter(  
	//							new BufferedWriter(new OutputStreamWriter(  
	//									socket.getOutputStream())), true);
	//
	//				} catch (IOException e) {
	//					// TODO Auto-generated catch block
	//					e.printStackTrace();
	//				}  
	//			}
	//			else
	//			{
	//				LogUtil.e("ZKCOCKET","receiveSocket is null");
	//				return;
	//			}
	//
	//			while(true && null != out)
	//			{
	//				byte[] buf = DataPackage.composeMsg((short)1214, (short)0x0001, null);
	//				out.println(buf);
	//				try {
	//					Thread.sleep(HEARTBEAT_TIMEOUT);
	//				} catch (InterruptedException e) {
	//					// TODO Auto-generated catch block
	//					e.printStackTrace();
	//				}
	//			}
	//
	//		};
	//	};

}
